<?php
/**
 * 获取微信用户信息并插入wechat_userinfo_new表
 * @author panchenxing@star-net.cn
 * @copyright  ktvme. All Rights Reserved.
 * @version $Id: Email.php 3 2017-05-08 03:02:47Z chendanming $
 */

namespace app\console\swooletask\logic;


use app\wechat\model\WechatUserError;
use think\Log;
use app\wechat\service\Wechat;
use app\wechat\model\WechatUserInfoNew;

class WechatUserInfo {

    /**
     * 获取微信用户信息并插入wechat_userinfo_new表
     * @param $wechat
     * @return array
     */
    public function wechatUserInfo($wechat){
//        Log::record(['more_info' => ['swoole_server_onreceive'=>json_encode($wechat)]], 'elk');
//        Log::save();
        $list = $wechat['list'];
        $userID = array_column($list,'UserID');
        $userList = [];
        foreach($list as $value) {
            $userList[] = [
                'openid' => $value['OpenID'],
                'lang'   => 'zh_CN'
            ];
        }
        $wechatService = new Wechat();
        $ret  = $wechatService->getUserInfo($userList);
        if(!$ret || $ret['errcode']){
            Log::record(json_encode(['get_userinfo_error' => $ret]), 'elk_more_info','wechat_userinfo');
            //Log::save();
            //失败的数据插入wechat_user_error表
            $wechatUserErrorModel = new WechatUserError();
            $result = $wechatUserErrorModel->InsertOpenidList($list);
            return $result;
        }
        $ret = $ret['user_info_list'];
        $userInfoList=[];
        foreach($ret as $key => $value) {
            if($value['subscribe'] == 0) continue;  //未关注
            $userInfo = [
                'UserID' => $userID[$key],
                'Sex'=>$value['sex'],
                'City'=>$value['city'],
                'Province'=>$value['province'],
                'Country'=>$value['country'],
                'Language'=>$value['language'],
                'HeadImgURL'=>$value['headimgurl'],
                'SubscribeTime'=>$value['subscribe_time'],
                'OpenID'=>$value['openid'],
                'TagidList'=>json_encode($value['tagid_list']),
            ];
            //微信昵称特殊昵称过滤处理
            $match = array();
            preg_match_all('/[\x{4e00}-\x{9fa5}A-Za-z0-9_]+/u', $value['nickname'], $match);
            $wxNickname           = implode("", $match[0]);
            $userInfo['Nickame'] = ($wxNickname != '' and mb_strlen($wxNickname, "UTF8") < 40) ? $wxNickname : '';
            $userInfoList[] = $userInfo;
            unset($userInfo);
        }
        //插入userinfonew表
        $wechatUserInfoNewModel = new WechatUserInfoNew();
        $result = $wechatUserInfoNewModel->insertUserInfoList($userInfoList);
        if(!$result){
            Log::record(json_encode(['insert_wechat_userinfo_error'=>$result]), 'elk_more_info','wechat_userinfo');
            Log::record(json_encode(['insert_wechat_userinfo_data'=>$userInfoList]), 'elk_more_info','wechat_userinfo');
            //Log::save();
        }
        return $result;
    }
}